package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("FoodtypeRestController")
public class FoodtypeRestController extends CmiEmaController {

	/**
	 * Create a new Foodtype entity
	 * 
	 */
	@RequestMapping(value = "/newFoodtype", method = RequestMethod.POST)
	@ResponseBody
	public Object newFoodtype(@RequestBody Foodtype foodtype) {
		foodtypeService.saveFoodtype(foodtype);
		return JSONObject.parse(cmiPsonService.toJsonString(foodtypeDAO.findFoodtypeByPrimaryKey(foodtype.getId()), 2));
	}

	@RequestMapping(value = "/restNewFoodtype", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewFoodtype(@RequestBody String foodtypeJson) {
		Foodtype foodtype = new Gson().fromJson(foodtypeJson, Foodtype.class);
		appendReferences(foodtype);
		foodtypeService.saveFoodtype(foodtype);
		return JSONObject.parse(cmiPsonService.toJsonString(foodtypeDAO.findFoodtypeByPrimaryKey(foodtype.getId()), 2));
	}

	@RequestMapping(value = "/saveFoodtype", method = RequestMethod.PUT)
	@ResponseBody
	public Foodtype saveFoodtype(@RequestBody Foodtype foodtype) {
		foodtypeService.saveFoodtype(foodtype);
		return foodtypeDAO.findFoodtypeByPrimaryKey(foodtype.getId());
	}

	@RequestMapping(value = "/restSaveFoodtype", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveFoodtype(@RequestBody String foodtypeJson) {
		Foodtype foodtype = new Gson().fromJson(foodtypeJson, Foodtype.class);
		appendReferences(foodtype);
		CmiPsonService cmiPsonService = new CmiPsonService();
		foodtypeService.saveFoodtype(foodtype);
		return JSONObject.parse(cmiPsonService.toJsonString(foodtypeDAO.findFoodtypeByPrimaryKey(foodtype.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteFoodtype/{foodtypeId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteFoodtype(@PathVariable Integer foodtypeId) {
		Foodtype foodtype = foodtypeDAO.findFoodtypeByPrimaryKey(foodtypeId);
		foodtypeService.deleteFoodtype(foodtype);
	}

	@RequestMapping(value = "/restConfirmDeleteFoodtypes")
	@ResponseBody
	public Object restConfirmDeleteFoodtypes(@RequestBody Set<Integer> deleteFoodtypesIds) {
		Set<Foodtype> deleteFoodtypes = foodtypeDAO.findFoodtypesByIds(deleteFoodtypesIds);
		Set<Foodtype> referencedFoodtypes = foodtypeService.loadReferenceFoodtypes(deleteFoodtypes);
		deleteFoodtypes.removeAll(referencedFoodtypes);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedFoodtypes);
		jsonObject.put("deleteEntitys", deleteFoodtypes);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteFoodtypes")
	@ResponseBody
	public Object restDeleteFoodtypes(@RequestBody Set<Foodtype> deleteFoodtypes) {
		Iterator<Foodtype> iterator = deleteFoodtypes.iterator();
		while (iterator.hasNext()) {
			Foodtype currentFoodtype = iterator.next();
			foodtypeService.deleteFoodtype(currentFoodtype);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listFoodtypes");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadFoodtype/{foodtypeId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodtype(@PathVariable Integer foodtypeId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(foodtypeDAO.findFoodtypeByPrimaryKey(foodtypeId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodtypeFoodtype/{foodtypeId}/foodtype", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodtypeFoodtype(@PathVariable Integer foodtypeId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(foodtypeDAO.findFoodtypeByPrimaryKey(foodtypeId).getParent(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadFoodtypeFoods/{foodtypeId}/foods/{relatedfoodId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodtypeFoods(@PathVariable Integer foodtypeId, @PathVariable Integer relatedfoodId,
			@RequestBody CmiPagination cmiPagination) {
		Food food = foodDAO.findFoodByPrimaryKey(relatedfoodId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(food, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodtypeFoodtypes/{foodtypeId}/foodtypes/{relatedfoodtypeId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodtypeFoodtypes(@PathVariable Integer foodtypeId, @PathVariable Integer relatedfoodtypeId,
			@RequestBody CmiPagination cmiPagination) {
		Foodtype foodtype = foodtypeDAO.findFoodtypeByPrimaryKey(relatedfoodtypeId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodtype, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodtypeStandards/{foodtypeId}/standards/{relatedstandardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodtypeStandards(@PathVariable Integer foodtypeId, @PathVariable Integer relatedstandardId,
			@RequestBody CmiPagination cmiPagination) {
		Standard standard = standardDAO.findStandardByPrimaryKey(relatedstandardId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(standard, 2, cmiPagination));
	}

	public void appendReferences(Foodtype foodtype) {

		Foodtype parent = foodtype.getParent();
		if (parent != null)
			foodtype.setParent(foodtypeService.findFoodtypeByPrimaryKey(parent.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Food> foodsForFoodtype = new HashSet<>();
		for (Food food_Foodtype : foodtype.getFoodsForFoodtype()) {
			foodsForFoodtype.add(foodService.findFoodByPrimaryKey(food_Foodtype.getId()));
		}
		foodtype.setFoodsForFoodtype(foodsForFoodtype);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodtype> foodtypesForParent = new HashSet<>();
		for (Foodtype foodtype_Parent : foodtype.getFoodtypesForParent()) {
			foodtypesForParent.add(foodtypeService.findFoodtypeByPrimaryKey(foodtype_Parent.getId()));
		}
		foodtype.setFoodtypesForParent(foodtypesForParent);

		// 引用表是纯联系表的情况
		Set<Standard> standardsForFoodtype = new HashSet<>();
		for (Standard standardForFoodtype : foodtype.getStandardsForFoodtype()) {
			standardsForFoodtype.add(standardService.findStandardByPrimaryKey(standardForFoodtype.getId()));
		}
		foodtype.setStandardsForFoodtype(standardsForFoodtype);
	}

	@RequestMapping(value = "/restGetFoodtypeFoodtype/{foodtypeId}/foodtype", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodtypeFoodtype(@PathVariable Integer foodtypeId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(foodtypeDAO.findFoodtypeByPrimaryKey(foodtypeId).getParent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodtypeFoods/{foodtypeId}/foods", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodtypeFoods(@PathVariable Integer foodtypeId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(foodtypeDAO.findFoodtypeByPrimaryKey(foodtypeId).getFoodsForFoodtype(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodtypeFoodtypes/{foodtypeId}/foodtypes", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodtypeFoodtypes(@PathVariable Integer foodtypeId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(foodtypeDAO.findFoodtypeByPrimaryKey(foodtypeId).getFoodtypesForParent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodtypeStandards/{foodtypeId}/standards", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodtypeStandards(@PathVariable Integer foodtypeId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(foodtypeDAO.findFoodtypeByPrimaryKey(foodtypeId).getStandardsForFoodtype(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListFoodtypes", method = RequestMethod.GET)
	@ResponseBody
	public Object restListFoodtypes() {
		return JSONObject.parse(cmiPsonService.toJsonString(foodtypeService.loadFoodtypes(), 2));
	}

	@RequestMapping(value = "/restListFoodtypesPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListFoodtypesPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = foodtypePaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Foodtype> foodtypes = foodtypeDAO.findAllFoodtypes(startResult, cmiPagination.getPaginationSize());
		String foodtypeString = cmiPsonService.toPsonString(foodtypes, 2, cmiPagination);

		return JSONObject.parse(foodtypeString);
	}

	@RequestMapping("/foodtypeSelectBox")
	@ResponseBody
	public JSONObject foodtypeSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键
			case "Food":
				entitySet = foodService.loadFoodsByIdSet(searchValue);
				break;
			case "Foodtype":
				entitySet = foodtypeService.loadFoodtypesByIdSet(searchValue);
				break;

			case "Standard":
				entitySet = standardService.loadStandardsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Food":
				entitySet = foodDAO.findAllFoods((pageNumber - 1) * paginationSize, paginationSize);
				count = foodService.countFoods();
				break;
			case "Foodtype":
				entitySet = foodtypeDAO.findAllFoodtypes((pageNumber - 1) * paginationSize, paginationSize);
				count = foodtypeService.countFoodtypes();
				break;

			case "Standard":
				entitySet = standardDAO.findAllStandards((pageNumber - 1) * paginationSize, paginationSize);
				count = standardService.countStandards();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Food":
				entitySet = foodDAO.findFoodByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodService.countFoodsByName(queryword);
				break;
			case "Foodtype":
				entitySet = foodtypeDAO.findFoodtypeByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodtypeService.countFoodtypesByName(queryword);
				break;

			case "Standard":
				entitySet = standardDAO.findStandardByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = standardService.countStandardsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
